package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.RedisCacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * 任务接口实现类
 */
@Service
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    @Autowired
    private RedisCacheService cacheService;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    /**
     * 添加任务
     *
     * @param task 任务对象
     * @return 任务id
     */
    @Override
    public Long addTask(Task task) {
        Future<Long> future = threadPoolTaskExecutor.submit(new Callable<Long>() {
            @Override
            public Long call() throws Exception {
                //1. 添加任务到数据库表中，taskinfo和taskinfologs
                boolean flag = saveTaskInfoToDb(task);
                if (flag) {
                    //添加任务到redis中
                    saveTaskInfoToRedis(task);
                }
                System.out.println("活跃线程数" + threadPoolTaskExecutor.getActiveCount());

                return task.getTaskId();
            }
        });
        try {
            return future.get();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 抽取的方法，保存数据到redis中
     *
     * @param task
     */
    private void saveTaskInfoToRedis(Task task) {
        String keySuffix = task.getTaskType() + "_" + task.getPriority();
        //获取未来五分钟的时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);

        //2. 添加任务到redis中
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            //如果执行时间小于等于当前系统时间则存入到list队列中

            cacheService.lLeftPush(ScheduleConstants.TOPIC + keySuffix, JSON.toJSONString(task));
        } else if (task.getExecuteTime() > System.currentTimeMillis() && task.getExecuteTime() <= calendar.getTimeInMillis()) {
            cacheService.zAdd(ScheduleConstants.FUTURE + keySuffix, JSON.toJSONString(task), task.getExecuteTime());
        }
    }

    /**
     * 抽取的新增数据到数据库表中的方法
     *
     * @param task
     * @return
     */
    private boolean saveTaskInfoToDb(Task task) {
        Taskinfo taskinfo = new Taskinfo();
        BeanUtils.copyProperties(task, taskinfo);
        taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
        taskinfoMapper.insert(taskinfo);

        //给task对象赋值
        task.setTaskId(taskinfo.getTaskId());

        TaskinfoLogs taskinfologs = new TaskinfoLogs();
        BeanUtils.copyProperties(taskinfo, taskinfologs);
        taskinfologs.setVersion(1);
        taskinfologs.setStatus(ScheduleConstants.SCHEDULED);

        int insert = taskinfoLogsMapper.insert(taskinfologs);
        return insert == 1;
    }

    /**
     * 按照类型和优先级来拉取任务
     * 消费任务，一定是从redis中list队列中拉取任务，不涉及zset队列
     *
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task poll(int type, int priority) {
        //使用多线程的方式
        Future<Task> future = threadPoolTaskExecutor.submit(new Callable<Task>() {
            @Override
            public Task call() throws Exception {
                String keySuffix = type + "_" + priority;
                //1. 从redis的list中取出数据并删除
                String taskStr = cacheService.lRightPop(ScheduleConstants.TOPIC + keySuffix);
                if (taskStr != null) {
                    //3. 把获取到taskStr转化成对象类型，从而获取taskId地址
                    Task task = JSON.parseObject(taskStr, Task.class);
                    //2. 修改数据库的表，删除任务表以及修改任务日志表的状态以及version
                    taskinfoMapper.deleteById(task.getTaskId());
                    TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(task.getTaskId());
                    if (taskinfoLogs != null) {
                        taskinfoLogs.setStatus(ScheduleConstants.EXECUTED);
                        //按照正常来说我们还要对version更新，此时不需要，因为mp已经集成version乐观锁
                        //taskinfoLogs.setVersion();
                        taskinfoLogsMapper.updateById(taskinfoLogs);
                    }
                    //4. 返回数据
                    return task;
                }
                return null;
            }
        });
        try {
            return future.get();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 定时同步刷新数据，从Zset中到list中
     * 定时任务的方法中没有参数，因为这个方法不被任何外界给调用
     * 每分钟执行一次
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    //@Scheduled(cron = "*/1 * * * * ?")
    public void refreshTaskFromZsetToList() {

        threadPoolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                //暂时把锁去掉，避免影响测试
                // String token = redisCacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
                //if(StringUtils.isNotBlank(token)){
                System.out.println(System.currentTimeMillis() / 1000 + "执行了定时任务");

                try {
                    //加入休眠时间
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


                //1. 获取zset中的所有key
                Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");//future_*
                if (futureKeys != null && futureKeys.size() > 0 ) {
                    //2. 判断数据是否到期
                    for (String futureKey : futureKeys) {
                        /**
                         * 参数1表示具体的key
                         * 参数2表示分值的最小值
                         * 参数3表示分值的最大值,最大值是当前系统时间，表示所有的数据都是到期的数据
                         * 返回值所有到期的数据的value
                         */
                        Set<String> taskSet = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());

                        if (!taskSet.isEmpty()) {
                            /**
                             *  3.同步数据到list
                             *  refreshWithPipeline(String future_key,String topic_key,Collection<String> values)
                             *  利用管道的方式进行同步操作
                             *  参数1表示未来数据的key
                             *  参数2表示list队列中的key
                             *  参数3表示同步的数据
                             */
                            //获取list队列的key
                            String keySuffix = futureKey.substring(7);
                            String listKey = ScheduleConstants.TOPIC + keySuffix;
                            cacheService.refreshWithPipeline(futureKey, listKey, taskSet);
                            System.out.println("成功的将" + futureKey + "下的当前需要执行的任务数据刷新到" + listKey + "下");
                        }
                    }
                }
            }
        });

    }

    /**
     * 同步数据从db到redis中，定时任务，每五分钟执行一次
     */
    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadDataToRedis(){
        //1.清空redis
        Set<String> listkeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        Set<String> zsetkeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        cacheService.delete(listkeys);
        cacheService.delete(zsetkeys);

        //2.从数据库表中查询小于等于未来5分钟的数据
        //获取未来五分钟的时间
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);

        LambdaQueryWrapper<Taskinfo> queryWrapper = Wrappers.<Taskinfo>lambdaQuery();
        queryWrapper.le(Taskinfo::getExecuteTime,calendar.getTime());
        List<Taskinfo> taskinfos = taskinfoMapper.selectList(queryWrapper);

        //3.保存到redis中
        if(taskinfos!=null && taskinfos.size()>0) {
            for (Taskinfo taskinfo : taskinfos) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo, task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                saveTaskInfoToRedis(task);
            }
        }
    }
}
